package com.qf.servlet;

import com.qf.constant.MessageConstant;
import com.qf.pojo.User;
import com.qf.service.UserService;
import com.qf.service.impl.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

/**
 * @Author AzureSky_X
 * @Date 2021/1/12 20:27
 * @Version 1.0
 * 插入用户
 */
@WebServlet("/insertUser")
public class InsertUserController extends HttpServlet {
    private UserService userService=new UserServiceImpl();

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        /**
         * Object bean,Map properties
         * bean:组件，模型，Java实体
         * Map:数据
         * 如果map中的数据有key跟Java实体的属性是一致的，那么就可以使用如下API进行封装
         * 把map中的数据封装到Java实体对象中
         */
        String errorMessage="";
        try {
        Map<String,String []> parameterMap = request.getParameterMap();
        User user=new User();
        //把map中的数据放到User对象中
        BeanUtils.populate(user,parameterMap);
        System.out.println(user);

        //调用业务逻辑层实现增加功能
        userService.insertUser(user);

        //插入后重新展示所有用户的信息
        response.sendRedirect(request.getContextPath()+"/user/list");

        return;
        } catch (NumberFormatException e){
            errorMessage = "不要乱传ID,ID必须是整形的";
        } catch (RuntimeException e) {
            e.printStackTrace();
            errorMessage = MessageConstant.DB_ERROR;
        } catch (Exception e) {
            errorMessage = MessageConstant.COMMON_ERROR;
        }
        response.getWriter().write("<script>alert('"+errorMessage+"')</script>");
    }

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}